// @flow
import React from 'react'
import styles from './DevicePoint.css'
import { Table, Select, message } from 'antd'
const Option = Select.Option
import R from 'ramda'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
message.config({
  top: 100
})

type Props = {
  location: Object,
  pointData: Array<Object>,
  getPointData: Function,
  partData: Array<Object>,
  devicePoint: Array<Object>,
  deviceId: number
}
type States = {
  pointData: Array<Object>,
  parts: string,
  point: string
}
class DevicePoint extends React.Component {
  state: States
  props: Props
  addPoint: Function
  changeParts: Function
  changePoint: Function
  deletePoint: Function
  selectParts: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      pointData: [],
      parts: '',
      point: ''
    }
    this.addPoint = this.addPoint.bind(this)
    this.changeParts = this.changeParts.bind(this)
    this.changePoint = this.changePoint.bind(this)
    this.deletePoint = this.deletePoint.bind(this)
  }
  deletePoint (item: Object) {
    const { getPointData } = this.props
    universalFetch(`${__SERVICE_API__}device/templates/devices/points/${item.rid}`, {
      method: 'Delete'
    })
    .then(res => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      message.success('测点删除成功')
      getPointData()
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
      message.error('测点删除失败 ')
    })
  }
  changePoint (value: any) {
    this.setState({
      point: value
    })
  }
  changeParts (value: any) {
    this.setState({
      parts: value
    })
  }
  componentWillReceiveProps (nextProps: Object) {
    const component = this
    if (!R.equals(nextProps, this.props)) {
      this.setState({
        pointData: nextProps.pointData.map((item, index) => {
          return {
            key: 'pointData' + index,
            parts: item.deviceName,
            point: item.sensorName,
            operate: <span className={styles['operate']} title='删除测点'
              onClick={function () { component.deletePoint(item) }}>
              <i className='fa fa-minus-circle' aria-hidden='true' />
            </span>
          }
        })
      })
    }
  }
  addPoint () {
    const { parts, point } = this.state
    const { deviceId, getPointData } = this.props
    if (parts && point) {
      const postData = {
        rootId: deviceId,
        points: [{
          deviceId: parts,
          monitorPointId: point.slice(0, point.indexOf('&'))
        }]
      }
      universalFetch(`${__SERVICE_API__}device/templates/devices/points`, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(postData)
      })
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        getPointData()
        message.success('测点添加成功')
      })
      .catch((error) => {
        handleFetchError(error)
        message.error('测点添加失败')
      })
    } else {
      message.error('请选择部件和测点！')
    }
  }
  render () {
    const { partData, devicePoint } = this.props
    const { pointData } = this.state
    const columns = [{
      title: '部件',
      dataIndex: 'parts',
      key: 'parts',
      width: '40%'
    }, {
      title: '测点',
      dataIndex: 'point',
      key: 'point',
      width: '40%'
    }, {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      width: '20%'
    }]
    const dataSource = [{
      key: 10000,
      parts: <span><Select showSearch
        filterOption={(input, option) => {
          return option.props.children.indexOf(input) >= 0
        }} placeholder='请选择部件' onChange={this.changeParts}>
        {
          partData.map((part, index) => {
            return <Option value={part.id + ''} key={'part' + index}>{part.name}</Option>
          })
        }
      </Select></span>,
      point: <span><Select showSearch
        filterOption={(input, option) => {
          return option.props.children.indexOf(input) >= 0
        }} placeholder='请选择测点' onChange={this.changePoint}>
        {
          devicePoint.map((point, index) => {
            return <Option value={point.id + '&' + point.rid} key={'point' + index}>{point.sensorName}</Option>
          })
        }
      </Select></span>,
      operate: <span className={styles['operate']} onClick={this.addPoint} title='保存测点'>
        <i className='fa fa-plus-circle' aria-hidden='true' />
      </span>
    }]
    return (
      <div className={styles['main']}>
        <Table columns={columns} pagination={false} dataSource={pointData.concat(dataSource)} />
      </div>
    )
  }
}

export default DevicePoint
